package cn.livingCloud.controller.core.validator;

import cn.livingCloud.dto.PushGroupFormDto;
import org.quartz.CronScheduleBuilder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by DingJie on 2016/6/21.
 */
@Component
public class PushGroupFormDtoValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return PushGroupFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", null, "组名不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cronExpression", null, "表达式不能为空");
        PushGroupFormDto formDto = (PushGroupFormDto) target;
        String cronExpression = formDto.getCronExpression();
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            scheduleBuilder.build();
        } catch (Exception e) {
            errors.rejectValue("cronExpression", null, "表达式错误,请根据语法填写表达式");
        }
    }
}
